package com.huishi.handler.thread.task;

import com.huishi.entity.DataSource;
import com.huishi.handler.thread.ThreadDataKeeper;
import com.huishi.ui.component.ProgressDialog;
import com.huishi.util.DBUtils;
import com.huishi.util.FileUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Queue;

/**
 * 监视sql队列，执行sql
 */
@Slf4j
public class Writer implements Runnable {

    private final DataSource sourceDS;

    private final DataSource targetDS; // 目标数据源
    private final String targetDB; // 目标库名

    private final ThreadDataKeeper threadDataKeeper; // 数据
    private final ProgressDialog progressDialog;
    private String syncTable; // 正在同步的表

    private Long taskId;

    public Writer(DataSource targetDS, String targetDB, ThreadDataKeeper threadDataKeeper, ProgressDialog progressDialog, long taskId) {
        this.targetDS = targetDS;
        this.targetDB = targetDB;
        this.threadDataKeeper = threadDataKeeper;
        this.progressDialog = progressDialog;

        this.sourceDS = threadDataKeeper.getSourceDS();
        this.taskId = taskId;
    }

    @Override
    public void run() {
        long start = System.currentTimeMillis();
        Queue<String> executeSqlFile = threadDataKeeper.getExecuteSqlFile();

        while (threadDataKeeper.getWriterRun()) {
            // 监控sql文件
            synchronized (threadDataKeeper.getExecuteSqlFile()) {
                while (executeSqlFile.isEmpty()) {
                    try {
                        executeSqlFile.wait(); // 如果要执行的sql为空，释放锁，进入等待，等待被唤醒
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        log.error("writer出错：", e);
                    }
                }
            }

            // 队列有元素了，被唤醒
            String sqlFile = executeSqlFile.poll();
            log.info("执行sql：{}", sqlFile);
            if (sqlFile == null) continue;
            boolean b = DBUtils.executeSQL(targetDS.getIp(), targetDS.getPort(), targetDS.getUserName(), targetDS.getPassword(), targetDB, sqlFile);

            // 更新状态
            if (syncTable == null) progressDialog.updateStatus(genSyncStatusText(sqlFile, true, null), true);

            else if (!syncTable.equals(getTableName(sqlFile))) { // 表同步完成
                progressDialog.updateStatus(genSyncStatusText(null, false, start), false);

                start = System.currentTimeMillis();

                progressDialog.updateStatus(genSyncStatusText(sqlFile, true, null), true);
            }

            syncTable = getTableName(sqlFile);

        }

        // 全部数据完成同步
        progressDialog.updateStatus(genSyncStatusText(null, false, start), false);
        threadDataKeeper.getProgressDialog().stopTimer();
        FileUtils.deleteDirectoryContents(new File(threadDataKeeper.getSqlFilePath()));
        threadDataKeeper.finishTask(taskId);
    }

    /**
     * 生成同步状态信息
     *
     * @param sqlFile
     * @param flag    true表示正在同步，false表示同步完成
     * @return
     */
    private String genSyncStatusText(String sqlFile, boolean flag, Long startTime) {
        String statusText;
        if (flag)
            statusText = "[Status][Sync] Synchronizing: " + sourceDS.getSourceName() + ".`" + threadDataKeeper.getSourceDB() + "`.`"
                    + getTableName(sqlFile) + "` -> " + targetDS.getSourceName() + ".`" + targetDB + "`.`" + getTableName(sqlFile) + "`";

        else statusText = "[Status][Sync] Time elapsed for " + syncTable + " -> " + syncTable + "："
                + (System.currentTimeMillis() - startTime) / 1000.0 + "s\n";

        return statusText;
    }

    private String getTableName(String sqlFile) {
        String[] split = sqlFile.split("/");
        return split[split.length - 1].split("-")[0];
    }

    public static void main(String[] args) {
        long cost = 34;
        System.out.println(cost / 1000.0);
    }


}
